<template>
  <div class="login-container">
    <h1>欢迎使用AgriVista系统！</h1>
    <form @submit.prevent="handleLogin">
      <div class="input-group">
        <input type="text" placeholder="账号（字母、数字、下划线，4-20字符）" v-model="user_account" required />
        <p v-if="accountError" class="error-message">{{ accountError }}</p>
      </div>
      
      <div class="input-group">
        <input type="password" placeholder="密码（字母、数字、下划线，6-20字符）" v-model="user_pwd" required />
        <p v-if="pwdError" class="error-message">{{ pwdError }}</p>
      </div>
      
      <p class="register-text">没有账号？<a href="#" @click.prevent="goToRegister">去注册</a></p>
      <div class="button-group">
        <button type="submit">登录</button>
        <button type="button" @click="goToRegister">注册</button>
      </div>
    </form>
    <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
    <p v-if="successMessage" class="success-message">{{ successMessage }}</p>
  </div>
</template>

<script>
import { getUser } from '@/api/user';
import axios from 'axios'; // 导入 axios

export default {
  data() {
    return {
      user_account: '',
      user_pwd: '',
      accountError: '',
      pwdError: '',
      errorMessage: '',
      successMessage: '' // 定义 successMessage 属性
    };
  },
  methods: {
    validateInput() {
      // 验证账号
      const accountRegex = /^[a-zA-Z0-9_]{4,20}$/;
      if (!accountRegex.test(this.user_account)) {
        this.accountError = '账号格式错误';
      } else {
        this.accountError = '';
      }
      
      // 验证密码
      const pwdRegex = /^[a-zA-Z0-9_]{6,20}$/;
      if (!pwdRegex.test(this.user_pwd)) {
        this.pwdError = '密码格式错误';
      } else {
        this.pwdError = '';
      }
      
      // 返回验证是否通过
      return this.accountError === '' && this.pwdError === '';
    },
    async handleLogin() {
      if (!this.validateInput()) {
        return;
      }
      
      try {
        // const response = await axios.post('http://172.20.2.46:5000/user/getUser', {
        //   user_account: this.user_account,
        //   user_pwd: this.user_pwd
        // });
        const response = await getUser(this.user_account,this.user_pwd)
        const data = response.data[0];
        console.log('登录响应数据:', data);
        if (response.code === 200 && data.length !== 0) {
          this.successMessage = '登录成功';
          this.errorMessage = '';
          alert('登录成功');
          localStorage.setItem('userId',data.user_id)
          this.$router.push('/');
        } else {
          this.errorMessage = data.message || '登录失败,请先注册！';
          this.successMessage = '';
          this.clearInputFields(); // 清空输入栏内容
        }
      } catch (error) {
        console.error('登录失败:', error);
        if (error.response) {
          // 请求已发出，但服务器响应的状态码不在 2xx 范围内
          this.errorMessage = error.response.data.message || '登录失败！请注册';
        } else if (error.request) {
          // 请求已发出，但没有收到响应
          this.errorMessage = '服务器错误，请稍后再试';
        } else {
          // 在设置请求时发生了一些事情，触发了错误
          this.errorMessage = '请求配置错误';
        }
        this.successMessage = '';
        this.clearInputFields(); // 清空输入栏内容
      }
    },
    goToRegister() {
      this.$router.push('/register');
    },
    clearInputFields() {
      this.user_account = '';
      this.user_pwd = '';
      this.accountError = '';
      this.pwdError = '';
    }
  }
};
</script>

<style scoped>
.login-container {
  width: 100%;
  height: 100%;
  margin: 50px auto;
  text-align: center;
  /* background-image: url('../assets/image/背景3.jpeg'); */
}

form {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 30px;
  width: 100%;
  max-width: 350px;
  margin: 0 auto;
}

.input-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

.register-text {
  margin-bottom: 20px;
  text-align: right;
  margin-right: 65px;
  font-size: 12px;
}

.button-group {
  display: flex;
  gap: 50px;
  justify-content: center; 
  margin-top: 10px;
  transform: translateY(-40px);
}

button {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button[type="submit"] {
  background-color: #ccc;
  color: white;
}

button[type="button"] {
  background-color: white;
  border: 1px solid #ccc;
}

a {
  text-decoration: none;
  color: #333;
}

.error-message {
  color: red;
  font-size: 12px;
  margin: 0;
  white-space: nowrap;
  text-align: center;
  margin-top: 10px;
}

.success-message {
  color: green;
  font-size: 12px;
  margin: 0;
  white-space: nowrap;
  text-align: center;
  margin-top: 10px;
}
</style>